import {
  PoseLandmarker,
  FilesetResolver,
  DrawingUtils
} from "../pose/vision.js";
    //websocketClient
    var client = null;

    //获取accessToken，简单的请求下后台接口判断accessToken是否正确
    //accessToken默认为123456
    //如果token有问题，不进行连接
    var accessToken = getQueryVariable("accessToken") ;

    //请求Token信息验证
    $.ajax({
        url:  window.location.origin + '/tokenController/check?accessToken=' + accessToken,
        type: 'get',
        success: function (res) {
            if(res === "success"){
                //启动远程桌面
    			startRemoteWin();
            }else {
            	alert("accessToken check error.");
            }
        },
        error: function (result) {

        }
    });
    //Jquery禁用网页右键菜单
//    $(document).bind("contextmenu",function(e){
//        return false;
//    });
    //远程桌面连接函数
    function startRemoteWin(options){
        const canvasElement = document.getElementById(
          "output_canvas"
        );
        const canvasCtx = canvasElement.getContext("2d");
        const drawingUtils = new DrawingUtils(canvasCtx);
    	//修改title
    	$('title').html("WEB远程桌面【连接中...】");
        client = new WebsocketClient();
        var currentStep = StepType[2];
        var leftStep = new FootStep2();
        var rightStep = new FootStep2();
        function leftStepListener(stepType, keyType, position){
              sendMsg(stepType, keyType);
          }
        function rightStepListener(stepType, keyType, position){
              sendMsg(stepType, keyType);
        }
        function sendMsg(stepType, keyType){
            currentStep = stepType;
               var keyCode = -1;
                switch (stepType) {
                  case "left":
                    keyCode = 37;
                    break;
                  case "down":
                    keyCode = 40;
                    break;
                  case "up":
                    keyCode = 38;
                    break;
                  case "right":
                    keyCode = 39;
                    break;
                  default:
                }
                if (keyCode == -1) {
                  return;
                }
//                var obj = new Object();
//                obj.openType = keyType;
//                obj.keyCode = keyCode;
//                client.sendClientData(obj);
        }
        leftStep.setStepListener(leftStepListener);
        rightStep.setStepListener(rightStepListener);
        var stepAdapter = new StepAdapter();
        leftStep.setStepAdapter(stepAdapter);
        rightStep.setStepAdapter(stepAdapter);
        //执行连接操作
        client.connect({
            onError: function (error) {
                //连接失败回调
                console.log("Error");

                //设置连接失败后的title
                $('title').html("WEB远程桌面【连接失败】");

            },
            onConnect: function () {
                //连接成功回调
                console.log("连接成功回调\r\n");

                //设置成功连接后的title
                $('title').html("WEB远程桌面【连接成功】");

            },
            onClose: function () {
                //连接关闭回调
                console.log("\rconnection closed, now reconnect comtempt..");
                //alert("Websocket连接已关闭");
                startRemoteWin();
            },
            onData: function (data) {
              var result = JSON.parse(data);
              if(result.landmarks != "undefined"){
                  canvasCtx.save();
                  var landmark = result.landmarks;
                  canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
                  drawingUtils.drawLandmarks(landmark, {
                            radius: 4,
                            color:"orange"
                    });
                  drawingUtils.drawConnectors(landmark, PoseLandmarker.POSE_CONNECTIONS, {color:"white"});
                  try{
                      var leftFoot = landmark[32];
                      var rightFoot = landmark[31];
                      leftStep.update(leftFoot);
                      rightStep.update(rightFoot);
                      stepAdapter.update(leftFoot, rightFoot);
                      for (var i = 0; i < stepAdapter.steps.length; i++) {
                            var stepPosition = stepAdapter.steps[i];
                            canvasCtx.fillStyle = 'red';
                            canvasCtx.beginPath();
                            canvasCtx.arc(canvasElement.width*stepPosition.x, canvasElement.height*stepPosition.y, currentStep===stepPosition.stepType?10:5, 0, Math.PI * 2); // 在(100,100)位置画一个半径为20的圆
                            canvasCtx.fill();
                   }
                  } catch(e){
                     }
                  canvasCtx.restore();
              }
            }
        });
    }

    //获取浏览器地址上的url参数
    function getQueryVariable(variable){
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
        }
        return "";
    }

/**
开始脚步算法
**/
var KeyType = ["keydown", "keyup", "unknown"];
var StepType = ["left", "down", "up", "right", "unknown"];
class Position {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

const FOOT_CENTER_UPDATE_MIN_DIS_X = 0.3;
const CENTER_MIN_MOVE_DIS = 0.2;
class StepAdapter {
  constructor() {
    this.center = new Position(0.5, 0.85);
    this.updatePosition();
  }

  //当两脚距离大于某个值的时候计算中心点?
  update(leftFoot, rightFoot) {
    if (rightFoot.x - leftFoot.x > FOOT_CENTER_UPDATE_MIN_DIS_X) {
      this.center = new Position((rightFoot.x + leftFoot.x) / 2,
          (rightFoot.y + leftFoot.y) / 2 - 0.05);
        this.updatePosition();
    }
  }

  updatePosition() {
    var center = this.center;
    this.steps = [
      //0.3, 0.9
      new StepPosition(center.x - 0.2, center.y + 0.05, StepType[0]),
      //0.5, 0.85
      new StepPosition(center.x, center.y , StepType[1]),
      //0.5, 0.95
      new StepPosition(center.x, center.y + 0.1, StepType[2]),
      //0.7, 0.9
      new StepPosition(center.x + 0.2, center.y + 0.05, StepType[3]),
    ];
  }
}

class StepPosition extends Position {
  constructor(x,y,type){
    super(x,y);
    this.stepType = type;
  }
}

class FootStep {
  setStepListener(listener) {}
  setStepAdapter(stepAdapter) {}
  update(footPosition) {}
}

const UPDATE_FOOT_DIS = 0.01;
const CHANGE_STEP_DIS = 0.18;
class FootStep2 extends FootStep {

  constructor(){
      super();
      this._prePosition = new Position(0, 0);
      this._preStepType = StepType[4];
  }

  setStepListener(stepListener) {
    this._stepListener = stepListener;
  }

  update(footPosition) {
    this._footStep(footPosition);
  }

  _footStep(footPos) {
    if(this._stepAdapter=="undefined"){
      return;
    }
    if (footPos.x > 1 || footPos.y > 1) {
      return;
    }
    var _prePosition = this._prePosition;
    var _preStepType = this._preStepType;
    var _stepAdapter = this._stepAdapter;
    var _stepListener = this._stepListener;
    var move = new Position(
        footPos.x - _prePosition.x, footPos.y - _prePosition.y);
    if (Math.abs(move.x) >= CHANGE_STEP_DIS ||
       Math.abs(move.y) >= UPDATE_FOOT_DIS) {
      var _stepDistance = 1;
      var stepType = StepType["2"];
      for (var i = 0; i < _stepAdapter.steps.length; i++) {
        var stepPosition = _stepAdapter.steps[i];
        var stepDistanceX = stepPosition.x - footPos.x;
        var stepDistanceY = stepPosition.y - footPos.y;
        var stepDistance = Math.abs(stepDistanceX) + Math.abs(stepDistanceY);
        if (stepDistance < _stepDistance) {
          _stepDistance = stepDistance;
          stepType = stepPosition.stepType;
        }
      }
      //换脚步直接点击
      if(_preStepType != stepType) {
        _stepListener(_preStepType, KeyType[0], footPos);
        _stepListener(stepType, KeyType[1], footPos);
      }else {
        //相同脚步，连击判断
        if (move.y < 0) {
          _stepListener(_preStepType, KeyType[0], footPos);
        }else{
          _stepListener(stepType, KeyType[1], footPos);
        }
      }
      this._preStepType = stepType;
      this._prePosition = footPos;
    }
  }

  setStepAdapter(stepAdapter) {
    this._stepAdapter = stepAdapter;
  }
}
/**
结束脚步算法
**/